﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Speech.Synthesis;
using System.Globalization;
using System.Configuration;

namespace KD.Sms
{
    public class Voicer
    {
        private static Voicer OWNER = null;
        SpeechSynthesizer _CurrentSpeech = new SpeechSynthesizer();
        CultureInfo _CurrentCultureInfo = System.Windows.Forms.InputLanguage.CurrentInputLanguage.Culture;
        InstalledVoice _CurrentVoice;
        string _strVoiceName = string.Empty;
        bool _bAllowSound = false;
        /// <summary>
        /// 私有构造函数
        /// </summary>
        private Voicer()
        {
            if (ConfigurationManager.AppSettings["VoiceName"] != null)
                _strVoiceName = System.Configuration.ConfigurationManager.AppSettings["VoiceName"].ToString();
            if (!string.IsNullOrEmpty(_strVoiceName))
            {
                _CurrentVoice = null;
                foreach (InstalledVoice voice in _CurrentSpeech.GetInstalledVoices(_CurrentCultureInfo))
                {
                    if (voice.VoiceInfo.Name == _strVoiceName)
                    {
                        _CurrentVoice = voice;
                        break;
                    }
                }
            }
            else
                _CurrentVoice = _CurrentSpeech.GetInstalledVoices(_CurrentCultureInfo).FirstOrDefault();
            if (_CurrentVoice != null && _CurrentVoice.Enabled)
            {
                try
                {
                    _CurrentSpeech.SelectVoice(_CurrentVoice.VoiceInfo.Name);
                    _bAllowSound = true;
                }
                catch (Exception ex)
                {

                }
            }
            else
                _CurrentSpeech = null;
        }

        /// <summary>
        /// 获取类的唯一实例
        /// </summary>
        /// <returns></returns>
        public static Voicer Instance
        {
            get
            {
                if (Voicer.OWNER == null)
                {
                    Voicer.OWNER = new Voicer();
                }
                return Voicer.OWNER;
            }
        }

        /// <summary>
        /// 发送语音包
        /// </summary>
        /// <param name="_msg"></param>
        public void DoSendSound(string _strVoiceStr)
        {
            Thread thread = new Thread(new ParameterizedThreadStart(DoSound)) { IsBackground = true };
            thread.Start(_strVoiceStr);
        }

        /// <summary>
        /// 播报语音
        /// </summary>
        /// <param name="_strVoiceStr"></param>
        private void DoSound(object _strVoiceStr)
        {
            if (_CurrentSpeech != null)
                _CurrentSpeech.Speak("," + _strVoiceStr.ToString());
        }
    }
}
